package com.xuetang.controller.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xuetang.common.ApiResponse;
import com.xuetang.entity.Article;
import com.xuetang.entity.ArticleCategory;
import com.xuetang.service.ArticleService;
import com.xuetang.utils.UserUtils;

/**
 * 文章API接口控制器
 */
@RestController
@RequestMapping("/api/articles")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 获取文章列表
     */
    @GetMapping("/list")
    public ApiResponse getArticleList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword) {

        Map<String, Object> result = articleService.getArticleList(page, size, category, keyword);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.get("list"));
        data.put("total", result.get("total"));
        data.put("page", page);
        data.put("pageSize", size);
        data.put("totalPages", Math.ceil((Integer) result.get("total") / (double) size));

        return ApiResponse.success(data);
    }

    /**
     * 获取文章详情
     */
    @GetMapping("/detail/{id}")
    public ApiResponse getArticleDetail(@PathVariable Long id) {
        Long userId = UserUtils.getCurrentUserId();

        // 增加浏览量
        articleService.incrementViewCount(id);

        // 获取文章详情
        Article article = articleService.getArticleWithFavoriteStatus(id, userId);
        if (article == null) {
            return ApiResponse.error(404, "文章不存在");
        }

        // 获取相关文章推荐
        List<Article> relatedArticles = articleService.getHotArticles(3);

        Map<String, Object> data = new HashMap<>();
        data.put("article", article);
        data.put("relatedArticles", relatedArticles);

        return ApiResponse.success(data);
    }

    /**
     * 获取文章分类列表
     */
    @GetMapping("/categories")
    public ApiResponse getCategories() {
        List<ArticleCategory> categories = articleService.getCategories();
        return ApiResponse.success(categories);
    }

    /**
     * 获取推荐文章列表
     */
    @GetMapping("/recommended")
    public ApiResponse getRecommendedArticles(@RequestParam(defaultValue = "5") Integer limit) {
        List<Article> articles = articleService.getRecommendedArticles(limit);
        return ApiResponse.success(articles);
    }

    /**
     * 获取热门文章列表
     */
    @GetMapping("/hot")
    public ApiResponse getHotArticles(@RequestParam(defaultValue = "5") Integer limit) {
        List<Article> articles = articleService.getHotArticles(limit);
        return ApiResponse.success(articles);
    }

    /**
     * 点赞文章
     */
    @PostMapping("/like/{id}")
    public ApiResponse likeArticle(@PathVariable Long id) {
        boolean success = articleService.likeArticle(id);
        return success ? ApiResponse.success() : ApiResponse.error("点赞失败");
    }

    /**
     * 收藏/取消收藏文章
     */
    @PostMapping("/favorite/{id}")
    public ApiResponse favoriteArticle(@PathVariable Long id) {
        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return ApiResponse.error(401, "未登录");
        }

        boolean isFavorite = articleService.toggleFavorite(id, userId);

        Map<String, Object> data = new HashMap<>();
        data.put("isFavorite", isFavorite);

        return ApiResponse.success(data);
    }

    /**
     * 检查文章是否已收藏
     */
    @GetMapping("/favorite/check/{id}")
    public ApiResponse checkArticleFavorite(@PathVariable Long id) {
        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return ApiResponse.error(401, "未登录");
        }

        boolean isFavorite = articleService.isArticleFavorited(id, userId);

        Map<String, Object> data = new HashMap<>();
        data.put("isFavorite", isFavorite);

        return ApiResponse.success(data);
    }

    /**
     * 获取用户收藏的文章列表
     */
    @GetMapping("/favorite/list")
    public ApiResponse getUserFavoriteArticles(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return ApiResponse.error(401, "未登录");
        }

        Map<String, Object> result = articleService.getUserFavoriteArticles(userId, page, size);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.get("list"));
        data.put("total", result.get("total"));
        data.put("page", page);
        data.put("pageSize", size);
        data.put("totalPages", Math.ceil((Integer) result.get("total") / (double) size));

        return ApiResponse.success(data);
    }

    /**
     * 根据分类获取文章列表
     */
    @GetMapping("/category/{category}")
    public ApiResponse getArticlesByCategory(
            @PathVariable String category,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        Map<String, Object> result = articleService.getArticlesByCategory(category, page, size);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.get("list"));
        data.put("total", result.get("total"));
        data.put("page", page);
        data.put("pageSize", size);
        data.put("totalPages", Math.ceil((Integer) result.get("total") / (double) size));

        return ApiResponse.success(data);
    }

    /**
     * 搜索文章
     */
    @GetMapping("/search")
    public ApiResponse searchArticles(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        Map<String, Object> result = articleService.searchArticles(keyword, page, size);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.get("list"));
        data.put("total", result.get("total"));
        data.put("page", page);
        data.put("pageSize", size);
        data.put("totalPages", Math.ceil((Integer) result.get("total") / (double) size));

        return ApiResponse.success(data);
    }

    /**
     * 获取所有标签
     */
    @GetMapping("/tags")
    public ApiResponse getAllTags() {
        List<String> tags = articleService.getAllTags();
        return ApiResponse.success(tags);
    }
}